#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月6日

@author: Administrator
'''
from django.dispatch.dispatcher import receiver
from funcresource.models import Functional, UserFunctional
from django.db.models.signals import post_save, pre_save
from funcresource import settings

@receiver(post_save, sender=Functional, dispatch_uid="pyonion.brand.save")
def functional_post_save_handler(sender, instance, raw, created, **kwargs):
    if not created and  instance.origin:
        #当功能的功能资源改变时，用户原功能将删除
        if instance.func_resource_id != instance.origin.func_resource_id:
            UserFunctional.objects.filter(func=instance.func_resource).update(state=settings.StateEnum.DELETED)
            
@receiver(pre_save, sender=Functional, dispatch_uid="pyonion.brand.save")
def functional_pre_save_handler(sender, instance, raw, **kwargs):
    if instance.id:
        origin = None
        try:
            origin = Functional.objects.get(id=instance.id)
        except Functional.DoesNotExist:
            pass
        instance.origin = origin
    else:
        instance.origin = None
        
